<?php

namespace app\shop\controller;


use app\common\model\ShopMessageTip;
use app\common\model\ShopStore;
use app\common\service\Status;
use app\shop\model\ShopStoreGoodsSpec;
use buildView\Button;
use buildView\Filter;
use think\Controller;
use buildView\Detail;
use buildView\Form;
use buildView\Grid;
use app\shop\model\ShopOrder;
use think\Db;
use think\facade\View;
use vendor\dayin\HttpClient;
use app\shop\model\ShopOrderRefund;

/**
 * 订单管理
 * Class Order
 * @package app\admin\controller
 */
class Order extends Controller
{
    /**
     * 列表
     * @auth true
     * @menu true
     * @return string
     */
    public function index()
    {
        $store = session('store');
        $grid = new Grid(new ShopOrder);
        $grid->model()->where('store_id',$store['id'])->where('type',1)->where('is_pay',1)->where('status','<>',8);
        $grid->setTitle('订单列表');
        $grid->setFromOpen();
        $grid->user()->headimg('会员')->display(function ($val, $data, $html) {
            return $html . '<br>' . $data['user']['nickname'];
        })->setExcelData(function($val,$data){
            return $data['user']['nickname'];
        })->image(50);
        // if ($store){
        //     $grid->where('store_id',$store['id']);
        // }else{
        //     $grid->store()->name('门店');
        // }
        $grid->store()->name('门店');
        
        $grid->order_no('订单编号')->setExcelData(function($val,$data){
            return ' '.$data['order_no'];
        })->hide();
        $grid->title('订单标题')->hide();
        $grid->status('订单状态')->using(Status::ORDERSTATUS())->hide();
        $grid->total_price('订单金额')->hide();
        $grid->pay_price('已支付金额')->hide();
        $grid->create_at('下单时间')->hide();
        $grid->pay_time('支付时间')->hide();
        $grid->home_address('地址')->setExcelData(function ($vals,$data){
            return Db::name('user')->where('id',$data['uid'])->find()['home_address'];
        });
        $grid->type('订单类型')->using(Status::SHOPTYPE())->badge();
        $grid->status('订单信息')->display(function ($val, $data, $html) {
            if (is_null($data['pay_time'])) {
                $pay_time = '--';
            } else {
                $pay_time = $data['pay_time'];
            }

            $html = "订单编号：<strong class='color-text'>{$data['order_no']}</strong><br>订单状态：{$html}<br>订单金额：<strong class='color-blue'>{$data['total_price']}</strong>&nbsp;&nbsp;已支付：<strong class='color-blue'>{$data['pay_price']}</strong><br>下单时间：{$data['create_at']}<br>支付时间：{$pay_time}";
            return $html;
        })->align('left')->excelClose()->using(Status::ORDERSTATUS())->badge();
        $grid->goods_record('商品信息')->display(function ($vals, $data) {
            $htmlArr = [];
            foreach ($vals as $val) {
                $htmlArr[] = "<p>{$val['good_title']}</p><p>{$val['spec_name']}</p><p class='color-desc'>售价：{$val['price']} 元 数量：{$val['num']}</p>";
            }
            $html = implode('<hr>', $htmlArr);
            return $html;
        })->minWidth(300)->setExcelData(function ($vals,$data){
            $html = '';
            foreach ($vals as $val) {
                $html .= "{$val['good_title']} {$val['spec_name']} 售价：{$val['price']} 元 数量：{$val['num']} ";
            }
            return $html;
        })->align('left');
        $grid->actions(function ($action, $data) {
            $action->hideEdit();
            $action->hideDel();
            if ($data['pay_type'] == 2 && $data['is_pay'] == 0 && $data['status'] == 1) {
                $button = new Button('已支付','normal','sm','layui-icon-rmb');
                $button->href(url('updatePayPrice') . '?id=' . $data['id'], 'modal');
                $action->append($button);
            }
            // 获取售后表里的数据
            $select = model("ShopOrderRefund")->where('order_id',$data['id'])->find();
            
            $store = session('store');///
            if ($data['type'] == 1 && ($data['status'] != 7 && $data['status'] != 6)) {
                if ($data['status'] == 2) {
                    $button2 = new Button('开始洗衣');
                    $button2->save($data['id'], ['status' => 2], url('begainActivity'), '确认开始？');
                    $action->append($button2);
                }
                if ($data['status'] == 3) {
                    $button3 = new Button('洗衣完成');
                    $button3->save($data['id'], ['status' => 3], url('begainActivity'), '确认完成？');
                    $action->append($button3);
                }
                if ($data['status'] == 4) {
                    $button4 = new Button('取件完成');
                    $button4->save($data['id'], ['status' => 4], url('begainActivity'), '订单是否已取件？');
                    $action->append($button4);
                }
                // 如果售后表status=4,已经退款
            }elseif($select['status'] == 4){
                $button5 = new Button('已经退款');
                $action->append($button5);
            }elseif($data['status'] == 7){//判断是否为已经取消
                $button6 = new Button('申请取消');
                // $button6->save($data['id'], ['status' => 2], url('begainActivity'), '确认开始？');
                $action->append($button6);
            }
        });
        $grid->filter(function (Filter $filter)use($store) {
            // if (!$store) {
            //     $data = ShopStore::field('id,name')->column('name','id');
            //     $filter->eq('store_id', '门店')->select($data);
            // }
            $data = ShopStore::field('id,name')->where('id',$store['id'])->column('name','id');
            $filter->eq('store_id', '门店')->select($data);
            $filter->like('user.nickname', '会员');
            $filter->like('user.phone', '手机号');
            $filter->eq('order_no', '订单号');
            $filter->eq('type', '订单类型')->select(Status::SHOPTYPE());
            $filter->eq('status', '订单状态')->select(Status::ORDERSTATUS());
            $filter->eq('pay_type', '支付方式')->select(Status::PAYTYPE());
            $filter->dateBetween('create_at', '下单时间');
        });
        $grid->hideDeletesButton();
        $grid->hideAddButton();
        $button1 = new Button('开始洗衣');
        $button1->saveAll(['status'=>2], url('batchBegainActivity'), '确认当前操作？');
        $grid->addTools($button1);

        $button2 = new Button('洗衣完成');
        $button2->saveAll(['status'=>3], url('batchBegainActivity'), '确认当前操作？');
        $grid->addTools($button2);

        $button2 = new Button('取件完成');
        $button2->saveAll(['status'=>4], url('batchBegainActivity'), '确认当前操作？');
        $grid->addTools($button2);
        return $grid->view();
        // $store = session('store');
        // // halt($store);
        // $storeOrderData = ShopOrder::with(['user','store'])->where('store_id',$store['id'])->where('is_pay',1)->where('type','in','1,2,3,4')->select();
        // // halt($storeOrderData);
        // View::assign([
        //     'orderdata'  => $storeOrderData
        // ]);
        // return View::fetch();
    }
    
    public function batchAction(){
        $orderid = $this->request->post('orderid');
        ShopOrder::mSave($orderid);
    }

    /**
     * 洗衣流程
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/10/8 17:08
     */
    public function begainActivity()
    {
        $order_id = $this->request->post('id');
        $status = $this->request->post('status');
        $store_id = $this->request->post('store_id');
        $order = ShopOrder::with('store')->where('status', $status)->get($order_id);
        if ($order) {
            switch ($status){
                case 8:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已接单";
                    $order->status = 2;
                    $order->store_id = $store_id;
                    break;
                case 3:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已洗衣结束,请尽快到店领取衣物";
                    $order->status = 4;
                    break;
                case 4:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已领取衣物";
                    $order->status = 5;
                    break;
                default:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已收件洗衣中,请耐心等待";
                    $order->status = 3;
                    break;
            }
            $order->save();
            if ($order['uid']){
                $data = [
                    'uid' => $order['uid'],
                    'title' => '校园快洗',
                    'content' => $content
                ];
                ShopMessageTip::create($data);
            }
            $this->success('成功','');
        } else {
            $this->error('该订单无效或已开始洗衣');
        }
    }

    /**
     * 批量洗衣流程
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/10/8 17:08
     */
    public function batchBegainActivity()
    {
        $orderId = $this->request->post('id');
        $status = $this->request->post('status');
        if (!$orderId) {
            $this->error('请选择订单处理~');
        }
        $order = ShopOrder::with('store')->whereIn('id',explode(',', $orderId))->where('status', $status)->select();
        if (!$order) {
            $this->error('请勾选正确状态的订单进行操作~');
        }
        $saveData = [];
        $msgData = [];
        if ($order) {
            foreach ($order as $orderData) {
                switch ($status){
                    case 2:
                        $content = "你的{$orderData['title']}({$orderData['store']['name']})订单已洗衣结束,请尽快到店领取衣物";
                        $saveData[] = [
                            'id' => $orderData['id'],
                            'status' => 3
                        ];
                        $msgData[] = [
                            'uid' => $orderData['uid'],
                            'title' => '校园快洗',
                            'content' => $content
                        ];
                        break;
                    case 3:
                        $content = "你的{$orderData['title']}({$orderData['store']['name']})订单已领取衣物";
                        $saveData[] = [
                            'id' => $orderData['id'],
                            'status' => 4
                        ];
                        $msgData[] = [
                            'uid' => $orderData['uid'],
                            'title' => '校园快洗',
                            'content' => $content
                        ];
                        break;
                        case 4:
                            $content = "你的{$orderData['title']}({$orderData['store']['name']})订单已领取衣物";
                            $saveData[] = [
                                'id' => $orderData['id'],
                                'status' => 5
                            ];
                            $msgData[] = [
                                'uid' => $orderData['uid'],
                                'title' => '校园快洗',
                                'content' => $content
                            ];
                            break;
                    default:
                        break;
                }
            }

            $shopOrder = new ShopOrder();
            $shopOrder->saveAll($saveData);
            $shopMessageTip = new ShopMessageTip();
            $shopMessageTip->saveAll($msgData);
            $this->success('成功','');
        } else {
            $this->error('该订单无效或已开始洗衣');
        }
    }

    /**
     * 详情
     * @auth true
     * @menu true
     * @return string
     */
    public function detail()
    {
        $detail = new Detail(new ShopOrder);
        $detail->setTitle('订单详情');
        $data = $detail->getModelData();
        $detail->layout('订单信息', 6, function ($detail) {
            $detail->type('订单类型')->using(Status::SHOPTYPE());
            $detail->order_no('订单号');
            $detail->freight_price('快递费');
            $detail->goods_price('商品总价');
            $detail->total_price('订单金额');
            $detail->is_pay('支付状态')->display(function ($val,$data,$html){
                if ($data['pay_type'] == 2 && $data['is_pay'] == 0 && $data['status'] == 1) {
                    $button = new Button('已支付','normal','sm','layui-icon-rmb');
                    $button->href(url('updatePayPrice') . '?id=' . $data['id'], 'modal');
                    $html = $button->render();
                }
                return $html;
            })->using(Status::PAYSTATUS())->badge();
            $detail->pay_type('支付方式')->using(Status::PAYTYPE());
            $detail->pay_no('微信流水号');
            $detail->pay_price('支付金额￥');
            $detail->pay_time('支付时间');
            $detail->status('订单状态')->using(Status::ORDERSTATUS())->badge();
            $detail->create_at('下单时间');
        })->layout('门店信息', 6, function ($detail) {
            $detail->store()->name('门店名称');
            $detail->store()->logo('Logo')->image(50, 50, 50);
            $detail->store()->full_address('地址');
        })->layout('会员信息', 6, function ($detail) {
            $detail->user()->nickname('会员昵称');
            $detail->user()->headimg('会员头像')->image(50, 50, 50);
        });
        $detail->hasManyArray('goods_record', '商品信息', 12, function ($detail) {
            $detail->good_title('商品标题');
            $detail->price('商品售价');
            $detail->num('数量');
        });
        return $detail->view();
    }

    public function remind_num(){
        $store = session('store');
        $count = ShopOrder::where('type',1)->where('status',2)->where('store_id',$store['id'])->count();
        $stock_warning = sysconf('stock_warning');
        $stock_num = ShopStoreGoodsSpec::whereRaw('stock < '.$stock_warning)->where('is_deleted',0)->count('DISTINCT gid');
        $this->success('成功','',[
            'order_num'=>$count,
            'stock_num'=>$stock_num,
        ]);
    }

    
    // public function aaa(){
    //     $str = strtotime("+200 second");
    //     celTime($str);
    // }
    
    /**
     * 打印订单号
     */
    public function printOrderDetail()
    {
        $path = app()->getModulePath() . 'view/build_view/printOrderDetail.html';
        $content = file_get_contents($path);
        $uid = $_REQUEST['uid'];
        $data = [];
        $goodsTitle = '';
        $userName = '';
        $userPhone = '';
        $count = 0;
        if ($uid) {
            $orderInfo = Db::name('shop_order')->where('uid', $uid)->order('create_at desc')->find();
            if ($orderInfo) {
                $orderData = Db::name('ShopOrderGoods')->where('order_id', $orderInfo['id'])->select();
                if ($orderData) {
                    foreach ($orderData as $orderVal) {
                        $goodsTitle .= $orderVal['good_title'].'*'.$orderVal['num'];
                        $count += $orderVal['num'];
                    }
                }
                $userInfo = Db::name('user')->where('id',$orderInfo['uid'])->find();
                $userName = $userInfo['nickname'];
                $userPhone = $userInfo['phone'];
                $data['order_on'] = $orderInfo['order_no'];
                $data['goods_title'] = '共'.$count.'件   '.$goodsTitle;
                $data['userName'] = $userName;
                $data['userPhone'] = $userPhone;
                
                if($orderInfo['status']==2){
                    //扫码成功/输入uid 将订单状态已预约2改为洗衣中3
                    $orderStatus3 = Db::name('shop_order')->where('uid', $uid)->where('status','2')->update(['status' => '3']);
                    // 记录第一次扫码的时间
                    $data_time = Db::name('shop_order')->where('uid', $uid)->update(['update_time' => strtotime("+70second")]);
                }elseif ($orderInfo['status']==3) {
                    if(time() >= $orderInfo['update_time']){
                        // 第二次扫码，将订单状态洗衣中3改为已完成
                        $orderStatus4 = Db::name('shop_order')->where('uid', $uid)->where('status','3')->update(['status' => '4']);
                    }else{
                        $data['errCode'] = true;
                        // $data['errText'] = "重复扫码！请".bcsub($orderInfo['update_time'],time())."后再扫码";
                        $data['errText'] = "重复扫码！请".celTime($orderInfo['update_time'])."后再扫码";
                    }
                }
            }
            return json_encode($data);
        }
        //订单信息
        return View::display($content, ['data'=>$data], ['strip_space' => false]);
    }

    /**
     * 打印订单
     */
    public function printOrder()
    {
        

        //调用打印接口
        error_reporting(E_ERROR|E_WARNING|E_PARSE|E_USER_ERROR|E_USER_WARNING);
        header('Content-Type:text/html;charset=utf-8');
        // $dayin = new HttpClient();
        $host = '192.168.0.201'; //接口IP或域名
        $port = '9100';                   //接口端口	

        $reqTime = $this->getMillisecond();    //请求时间
        $securityCode='';               //安全检验码 ★★★ 不同接口生成安全检验码的字符组装方式不同 ★★★
        $apiKey='';                     //api密钥
        $memberCode='';                 //商户编码
        $mode = '2';                    //打印类型
        $deviceID = '';                 //终端编号
        $msgNo = '';                    //订单编号
        $msgDetail = '';                //打印内容 ★★★ 不同型号的打印机打印指令不同，GP-TD2270打印内容为TSPL指令，GP-CH421D打印内容为ZPL指令，票据机支持普通文本内容 ★★★
        $charset = 1;                   //编码格式 ★★★ 票据机型、GP-TD2270请选择 1：gb18030，标签机GP-CH421D请选择 4：utf-8 ★★★
        $action = 'sendMsg';            //发送数据到打印机

        $reqTime = $this->getMillisecond();
        $securityCode = md5($memberCode.$deviceID.$msgNo.$reqTime.$apiKey);
        $url = $host.':'.$port.'/apisc/sendMsg';
        $content['charset'] = $charset;
        $content['reqTime'] = $reqTime;
        $content['memberCode'] = $memberCode;
        $content['deviceID'] = $deviceID;
        $content['securityCode'] = $securityCode;
		// 打印内容
        $content['msgDetail'] = $msgDetail;
        $content['msgNo'] = $msgNo;
		// reprint 是否验证订单编号，1：不验证订单编号，可重新打印订单
        $content['reprint'] = $reprint ?? 0;  
		// multi 是否多订单模式，默认0：为单订单模式，1：多订单模式，
		// 多订单模式下 $msgDetail 为json格式，格式为{"ordernum001":"msgDetail001","ordernum002":"msgDetail002"}
		// 多订单模式下订单编号不能重复，必须填写。建议最大订单数为50
        $content['multi'] = $multi ?? 0;    
		// 打印类型				   
        $content['mode'] = $mode;  
        // 打印联数		
        $content['times'] = '';  
        $res = $this->request_post($url, $content);
        echo $res;
    }

    //毫秒时间戳
    function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
    function request_post($url = '', $post_data = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

}
